package com.sum.tea.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.sum.common.bean.ReadMode
import com.sum.common.bean.ReaderExt
import com.sum.common.bean.Stats
import com.sum.common.bean.TagInfo
import com.sum.common.inter.OnInventoryListener
import com.sum.common.manager.UHFManager
import com.sum.common.utils.LogU
import kotlinx.coroutines.launch
import java.util.Collections

open class BaseViewModel:ViewModel() {
    protected val _tagList = MutableLiveData<List<TagInfo>>()
    val tagList: LiveData<List<TagInfo>> = _tagList

    private val _timerValue = MutableLiveData<Int>()
    val timerValue: LiveData<Int> = _timerValue

    protected val _stats = MutableLiveData<Stats>()
    val stats: LiveData<Stats> = _stats
    // 内存数据源
    val internalTagList = Collections.synchronizedList(mutableListOf<TagInfo>())
    private var lastUpdateTime = 0L
    private val UPDATE_INTERVAL = 100L
    private var justReadOnce = false
    fun setJustReadOnce(once:Boolean){
        justReadOnce = once
    }

    fun startReading(readMode: ReadMode) {
        setListener()
        val result = UHFManager.getInstance().currentManager.asyncStartReading(readMode)
        if(result == ReaderExt.READER_ERR.MT_OK_ERR){
            ToastUtils.showShort("startReading success")
        }
    }


    private fun setListener() {
        UHFManager.getInstance().currentManager.setOnInventoryListener(object : OnInventoryListener {
            override fun onInventoryListener(tagList: List<TagInfo>, stats: Stats) {
                LogU.d("onInventory", "tagList: ${tagList.size} ,stats:$stats")
                justSyncTagLists(tagList, stats)
                if(justReadOnce){
                    stopReading()
                }
            }


            override fun onError(error: ReaderExt.READER_ERR) {
                LogU.d("onInventory", "onError: $error")
            }

        })
    }


    private fun justSyncTagLists(tagList: List<TagInfo>, stats:Stats) {
        synchronized(internalTagList) {
            // 更新内存数据
            internalTagList.clear()
            internalTagList.addAll(tagList)

            // UI更新控制频率
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastUpdateTime >= UPDATE_INTERVAL) {
                lastUpdateTime = currentTime
                viewModelScope.launch {
                    _tagList.value = ArrayList(internalTagList) // 创建副本
                    _stats.value = stats
                    readTag(_tagList.value!!)
                }
            }
        }
    }

    open fun readTag(tagInfoList:List<TagInfo>){

    }


    fun stopReading() {
        UHFManager.getInstance().currentManager.asyncStopReading()
    }

    fun clearData() {
        synchronized(internalTagList) {
            internalTagList.clear()
            _timerValue.value = 0
            UHFManager.getInstance().currentManager.clearTagList()// 更新UI
            viewModelScope.launch {
                _tagList.value = emptyList()
                _stats.value = Stats()
            }
        }
    }

}